package com.dina.saas.peccancy.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.dina.saas.peccancy.domain.Detail;
import com.dina.saas.peccancy.domain.Peccancy;
import com.dina.saas.peccancy.domain.ResponsePeccMsg;

public class ShenZhenParser implements Parser {

	@Override
	public ResponsePeccMsg parseAll(String msg) {
		// TODO Auto-generated method stub
		ResponsePeccMsg peccMsg = new ResponsePeccMsg("listPecc", 1, "");
		if (msg == null) {
			peccMsg.setResultNote(Constants.HTTP_ERROR);
			return peccMsg;
		}
		Document doc = Jsoup.parse(msg);
		List<Object> peccancyArray = getPeccsArrayByDoc(doc);
		if (peccancyArray.size() > 0) {
			peccMsg.setTotalRecordNum(peccancyArray.size());
			peccMsg.setDetail(new Detail(peccancyArray));
			peccMsg.setResult(0);
		} else {
			peccMsg.setTotalRecordNum(peccancyArray.size());
		}
		return peccMsg;
	}

	private List<Object> getPeccsArrayByDoc(Document doc) {
		List<Object> peccancyArray = new ArrayList<Object>();
		Elements tables = doc.select("table:has(iframe)");
		if (tables.size() == 2) {
			Element e = tables.get(1);
			Elements trs = e.select("tr");
			if(trs.size()<=4){
				return peccancyArray;
			}
			trs.remove(0);
			trs.remove(0);
			trs.remove(trs.size() - 1);
			trs.remove(trs.size() - 1);
			for (int i = 0; i < trs.size(); i++) {
				Element tr = trs.get(i);
				Elements tds = tr.children();
				Peccancy pecc = new Peccancy();
				pecc.setId("" + i);
				for (int j = 0; j < tds.size(); j++) {
					Element td = tds.get(j);
					String value = td.html();

					switch (j) {
					case 0: {
						pecc.setTime(value);
						break;
					}
					case 1: {
						pecc.setPlace(value);
						break;
					}
					case 2: {
						value = value.replace("<br />", " ");
						pecc.setAction(value);
						break;
					}
					case 3: {
						// 执法单位
						break;
					}
					case 4: {
						pecc.setResult(value);
						break;

					}
					}
				}
				peccancyArray.add(pecc);
			}
		}
		return peccancyArray;
	}

	@Override
	public ResponsePeccMsg parsePeccs(ResponsePeccMsg peccMsg, String msg) {
		// TODO Auto-generated method stub
		return null;
	}

}
